<template>
    <div class="myEditor">
        <p>
            <span class="theme">
                <el-select v-model="language" size="mini" @change="languageChange" placeholder="请选择语言">
                    <el-option
                        v-for="item in languageOption"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </span>
        </p>
        <div id="container" ref="container" style="height:600px; width: 100%;"></div>
    </div>
</template>
<script>
import * as monaco from 'monaco-editor';
export default {
    props:{
      value: {
        type: String,
        default: ''
      }
    },
    watch: {
      value(newValue) {
        if (this.monacoEditor) {
          const editor = this.monacoEditor
          if (newValue !== editor.getValue()) {
            editor.setValue(newValue)
          }
        }
      }
    },
    data(){
      return{
        monacoEditor: null,
        languageOption:[
          {
              value:'html',
              label:'html'
          },
          {
              value:'xml',
              label:'xml'
          },
          {
              value:'json',
              label:'json'
          },
        ],
        language: 'json'
      }
    },
    mounted(){
      this.initEditor();
    },
    methods:{
      initEditor(){
        let self = this;
        self.$refs.container.innerHTML = '';
        self.monacoEditor = monaco.editor.create(self.$refs.container, {
            value: self.value,
            language: self.language,
            theme: 'vs',
            minimap: {
              enabled: false
            },
            // selectOnLineNumbers: true,
            // roundedSelection: false,
            // readOnly: false,        // 只读
            // cursorStyle: 'line',        //光标样式
            // automaticLayout: false, //自动布局
            // glyphMargin: true,  //字形边缘
            // useTabStops: false,
            // fontSize: 28,       //字体大小
            // autoIndent:true,//自动布局
        });
        //self.$emit('onMounted',self.monacoEditor);//编辑器创建完成回调
        self.monacoEditor.onDidChangeModelContent(function(event){
          const value = self.monacoEditor.getValue();
          if (self.value !== value) {
            self.$emit('change', value, event)
          }
        });
      },
      languageChange(val){
        this.initEditor();
      }
    }
}
</script>

